import InputArea from './components/InputArea';
import List from './components/List';
import { useEffect, useState } from 'react';

function randomColor() {
  const r = Math.floor(256 * Math.random());
  const g = Math.floor(256 * Math.random());
  const b = Math.floor(256 * Math.random());
  return `rgb(${r},${g},${b})`;
}


const App = () => {

  // 英雄列表数据
  const [list, setList] = useState([
    // {
    //   id: 12,
    //   name: 'xxx',
    //   bgColor: 'xxx',
    //   mainType: -1,
    //   subType: -1,
    //   playType: -1,
    // }
  ]);
  // 当前选中项的id
  const [currentId, setCurrentId] = useState(0);
  // 输入框中当前输入的内容
  const [inputValue, setInputValue] = useState('');
  // 更新输入内容
  function handleOnChange(value) {
    setInputValue(value);
    setCurrentId(0);
  }

  // 更新单选项切换
  function handleSelect(id) {
    setCurrentId(id);
  }

  useEffect(() => {
    // 发起网络请求
    fetch('/db/herolist.json')
      .then(response => {
        return response.json();
      })
      .then(jsonData => {
        const newList = jsonData.toReversed().map(item => ({
          id: item.moss_id,
          name: item.cname,
          bgColor: randomColor(),
          mainType: item.hero_type,
          subType: item.hero_type2 || -1,
          playType: item.pay_type || -1,
        }));
        setList(newList);
      });
  }, []);

  return (
    <div className="w-[1200px] mx-auto mt-50 mb-[50px] p-5 border-[#e8e8e8] border-[2px] border-t-[#d4d4d4] border-t-[3px]">
      <InputArea 
        onChange={handleOnChange} 
        onSelect={handleSelect}
        current={currentId}
        value={inputValue}
      />
      <List list={list} current={currentId} keyword={inputValue}/>
    </div>
  );
};

export default App;